package com.xbongbong.workflow.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.pojo.workflow.operate.dto.WorkflowApproveFailedDTO;
import com.xbongbong.paas.pojo.workflow.operate.dto.WorkflowUpdateBackDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.workflow.service.WorkflowDataProcessService;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2022/08/23 10:59
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/strategy")
public class WorkflowDataProcessController {

    @Resource
    private WorkflowDataProcessService workflowDataProcessService;

    @RequestMapping(value = "/approvalFailed", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String approvalFailed(@RequestBody @Valid WorkflowApproveFailedDTO workflowApproveFailedDTO, BindingResult br) throws Exception {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                workflowDataProcessService.approvalFailed(workflowApproveFailedDTO);
                response = new XbbResponse<>(new BaseVO());
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    @RequestMapping(value = "/updateBack", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateBack(@RequestBody @Valid WorkflowUpdateBackDTO workflowUpdateBackDTO, BindingResult br) throws Exception {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                workflowDataProcessService.updateBack(workflowUpdateBackDTO);
                response = new XbbResponse<>(new BaseVO());
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
}
